"""
错误处理工具
提供API错误处理和异常处理
"""
from flask import jsonify
from marshmallow import ValidationError

def register_error_handlers(app):
    """注册应用错误处理器"""
    
    @app.errorhandler(ValidationError)
    def handle_validation_error(e):
        """处理验证错误"""
        return jsonify({"msg": str(e), "errors": e.messages}), 400
    
    @app.errorhandler(400)
    def handle_bad_request(e):
        """处理错误请求"""
        return jsonify({"msg": "请求参数错误"}), 400
    
    @app.errorhandler(401)
    def handle_unauthorized(e):
        """处理未授权访问"""
        return jsonify({"msg": "未授权访问"}), 401
    
    @app.errorhandler(403)
    def handle_forbidden(e):
        """处理禁止访问"""
        return jsonify({"msg": "权限不足"}), 403
    
    @app.errorhandler(404)
    def handle_not_found(e):
        """处理资源不存在"""
        return jsonify({"msg": "资源不存在"}), 404
    
    @app.errorhandler(405)
    def handle_method_not_allowed(e):
        """处理方法不允许"""
        return jsonify({"msg": "方法不允许"}), 405
    
    @app.errorhandler(500)
    def handle_internal_server_error(e):
        """处理服务器内部错误"""
        return jsonify({"msg": "服务器内部错误"}), 500
    
class APIError(Exception):
    """API错误基类"""
    def __init__(self, message, status_code=400, payload=None):
        super().__init__(self)
        self.message = message
        self.status_code = status_code
        self.payload = payload
    
    def to_dict(self):
        """转换为字典"""
        rv = dict(self.payload or ())
        rv['msg'] = self.message
        return rv

class NotFoundError(APIError):
    """资源不存在错误"""
    def __init__(self, message="资源不存在", payload=None):
        super().__init__(message, 404, payload)

class UnauthorizedError(APIError):
    """未授权错误"""
    def __init__(self, message="未授权访问", payload=None):
        super().__init__(message, 401, payload)

class ForbiddenError(APIError):
    """禁止访问错误"""
    def __init__(self, message="权限不足", payload=None):
        super().__init__(message, 403, payload)

class BadRequestError(APIError):
    """错误请求错误"""
    def __init__(self, message="请求参数错误", payload=None):
        super().__init__(message, 400, payload)

def register_api_error_handlers(app):
    """注册API错误处理器"""
    
    @app.errorhandler(APIError)
    def handle_api_error(error):
        """处理API错误"""
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response 